package logintest;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

//登录校验
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.先拿到数据
        req.setCharacterEncoding("utf8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        //2.验证拿到数据是否正确
        if (username == null || password == null || username == "" || password == "") {
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("用户名或者密码不正确");
            return;
        }
        //   假定用户名是xiaohua,密码是123
        if (!username.equals("xiaohua")) {
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("用户名或者密码不正确");
            return;
        }
        if ( !password.equals("123")) {
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("用户名或者密码不正确");
            return;
        }
        HttpSession session =req.getSession(true);
        session.setAttribute("username",username);
        resp.sendRedirect("index");
    }
}
